package handler

import (
	"ast-ship/cache"
	"ast-ship/model"
	"ast-ship/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	//redis_key := "user_login" + username
	//errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	//if errCount >= 3 {
	//	c.JSON(200, gin.H{
	//		"code": 500,
	//		"msg":  "密码错误三次，禁止登录",
	//	})
	//	return
	//}
	var user model.User
	err := model.DB.Where("username = ?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		//cache.Rdb.Incr(cache.Ctx, redis_key)
		//if errCount == 2 {
		//	cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
		//	c.JSON(200, gin.H{
		//		"code": 500,
		//		"msg":  "密码错误三次",
		//	})
		//	return
		//}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	data := model.Article{
		Title:   title,
		Content: content,
	}
	err := model.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	redis_key := "article_add" + strconv.Itoa(int(data.ID))
	var article model.Article
	model.DB.Where("id = ?", data.ID).Find(&article)
	jsonData, _ := json.Marshal(article)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var article model.Article
	model.DB.Where("id = ?", id).First(&article)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": article,
	})
	return
}

func Delete(c *gin.Context) {
	id := c.Query("id")
	err := model.DB.Where("id = ?", id).Delete(&model.Article{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}

	redis_key := "article_add" + id
	cache.Rdb.Del(cache.Ctx, redis_key)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func List(c *gin.Context) {
	var article []model.Article

	redis_key := "article_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&article)

		jsonData, _ := json.Marshal(article)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": article,
	})
	return
}
